﻿namespace LS.Nc6.Web.Entry.Areas.Cms.Controllers
{
    /// <summary>
    /// 内容审核
    /// </summary>
    [Route("[area]/[controller]/[action]")]
    [Area("Cms")]
    [ApiDescriptionSettings("Default")]
    public class ContentCheckController : BaseAdminController
    {
        #region CmsContentCheckController
        private readonly ICmsContentCheckService _contentCheckService;
        private readonly ICmsContentService _contentService;
        private readonly ICache _cache;
        public ContentCheckController(ICmsContentCheckService contentCheckService, ICmsContentService contentService, IOptions<CacheOptions> cacheOptions, Func<string, ISingleton, object> resolveNamed)
            :base(cacheOptions, resolveNamed)
        {
            _contentCheckService = contentCheckService;
            _contentService = contentService;
            _cache = resolveNamed(cacheOptions.Value.CacheType.ToString(), default) as ICache;
        }
        #endregion

        #region 页面
        public ActionResult Index()
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRSH, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            return View();
        }
        public ActionResult Create()
        {
            SysPower(SysMenuConstant.MENU_CMS_NEWS_NRSH, SysMenuConstant.FUN_SELECT, UserInfo.ID.ToString());
            var model = new CmsContentCheckEntity();
    
            return View("Edit", model);
        }
        public async Task<ActionResult> AuditContent(string ids)
        {

            SysPower(new List<string> { SysMenuConstant.MENU_CMS_NEWS_NRSH, SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.MENU_CMS_NEWS_NRSS } , SysMenuConstant.FUN_AUDIT, UserInfo.ID.ToString());

            if (string.IsNullOrEmpty(ids))
            {
                return ErrorCustomMsg(ResponseHelper.PARAMETER_CSCW);
            }

            var contentList= await _contentService.List(a => ids.GetStringToLongArryNoNull().Contains(a.Id), a => a.Id, a => new { 
                a.Id, 
                a.Title,
                a.CreateDate,
                a.UserName,
                a.Checked
            });
            ViewBag.ContentNum = contentList.Count;
            ViewBag.ContentList = contentList;
            ViewBag.Ids =string.Join(",", contentList.Select(a => a.Id).ToList());
            ViewBag.CheckedList = CmsHelper.GetCheckedList();

            return View();
        }


        #endregion

        #region  公共方法
        [HttpGet]
        public async Task<ResponseResultDataList> GetList()
        {
            string keyword = RequestHelper.FilterParam(Request.Query["title"]);
            var page = Request.Query["page"].ToString().GetQueryValueOrNull<int>(1);
            var limit = Request.Query["limit"].ToString().GetQueryValueOrNull<int>(20);
            string field = Request.Query["field"];
            string order = Request.Query["order"];

            var expable = Expressionable.Create<CmsContentEntity, CmsChannelEntity>();
            expable.AndIF(!string.IsNullOrEmpty(keyword), (a,b) => a.Title.Contains(keyword));
            var exp = expable.ToExpression();
            var strField = RequestHelper.FilterParam(field);
            var strOrder = RequestHelper.FilterParam(order);

            Expression<Func<CmsContentEntity, CmsChannelEntity, object>> expressionOrder;
            if (string.IsNullOrEmpty(strField) || string.IsNullOrEmpty(strOrder))
            {
                expressionOrder = (a,b) => new { a.CreateDate };
            }
            else
            {
                //实现字段排序
                expressionOrder = (a,b) => new { a.CreateDate };
            }
          
            var result = await _contentService.PageDynamicLeftJoinList(exp, page, limit, expressionOrder, (a,b) => new {
                id = a.Id,
                title = a.Title,
                channelId=a.ChannelId,
                channelName = b.ChannelName,
                status = a.Checked,
                createDate = a.CreateDate,
                userName =a.UserName
            });
            return new ResponseResultDataList { code = ResponseHelper.SEUCCESSCODE, message = "请求成功", data = result.Item1, count = result.Item2 };
            
        }



        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> SaveData([FromBody] ContentAuditInput input)
        {
           
            long result = 0;
            try
            {
                bool power = SysPower(new List<string> { SysMenuConstant.MENU_CMS_NEWS_NRSH, SysMenuConstant.MENU_CMS_NEWS_NRGL, SysMenuConstant.MENU_CMS_NEWS_NRSS }, SysMenuConstant.FUN_AUDIT, UserInfo.ID.ToString(), false);

                if (!power)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_QXZU);
                }
                var ids = input.Ids.GetStringToLongArryNoNull();
                if (ids.Length == 0)
                {
                    return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
                }
                for (int i = 0; i < ids.Length; i++)
                {
                    var contentmodel = await _contentService.GetByIdAsync(ids[i]);
                    if (contentmodel != null)
                    {
                        await _contentCheckService.InsertAsync(new CmsContentCheckEntity
                        {
                            AdminId = UserInfo.ID,
                            ChannelId = contentmodel.ChannelId,
                            CheckDate = DateTime.Now,
                            CheckedLevel = 0,
                            Checked = input.AuditState,
                            ContentId = contentmodel.Id,
                            Reasons = input.AuditRemark
                        });
                        result++;
                    }
                }
                return ResponseHelper.SaveResult(result);
            }
            catch (Exception)
            {
               
            }
            return ResponseHelper.SaveResult(0);
        }


        [HttpPost]
        public async  Task<ResponseResult> Delete([FromBody]DeletDataInput input)
        {
            var r = SysPower(SysMenuConstant.MENU_CMS_NEWS_NRSH, SysMenuConstant.FUN_DELETE, UserInfo.ID.ToString(), false);
            if (!r)
            {
                return ResponseHelper.MessageResult(ResponseHelper.PERMISSION_WSCQX);
            }
            if (string.IsNullOrEmpty(input.Ids))
            {
                return ResponseHelper.MessageResult(ResponseHelper.PARAMETER_CSCW);
            }
            int result =await _contentCheckService.DeleteAsync(input.Ids.ToString());
            return ResponseHelper.DeleteResult(result);
        }

        #endregion


        #region 私有方法

        #endregion
    }
}